<script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue'
import { useRoomStore } from '@/stores/room'
import { useUserStore } from '@/stores/user'
import ws from '@/services/websocket'
import clickSound from '@/services/clickSound'
//父组建传过来的位置
const props = defineProps({
  // 父组件以 :slot-index 传入，这里用驼峰接收
  slotIndex: {
    type: [Number, String],
    default: null,
  }
})
const emit = defineEmits(['collapse'])
const roomStore = useRoomStore()
const userStore = useUserStore()
// 好友列表（响应式）
const friends = ref([])


// 邀请点击
function invite(friend){
  console.log('邀请好友:', friend?.user2, friend?.nickname2, '位置:', props.slotIndex)
  clickSound.play()

  //向服务器发送邀请信息
  try {
    const payload = {
      genre: 3,
      type: 'invitefriend',
      uid: userStore.uid,
      friend_uid: friend?.user2,
      rid: roomStore.room_id,
      nickname: userStore.nickename,
      pos: Number(props.slotIndex)
    }
    ws.send(JSON.stringify(payload))
    console.log('发送邀请：', payload)
  } catch (e) {
    console.error('发送邀请失败：', e)
  }
}

// 邀请发送结果提示
const inviteMsg = ref('')
let inviteMsgTimer = null
function showInviteMsg(text){
  inviteMsg.value = text
  if (inviteMsgTimer) clearTimeout(inviteMsgTimer)
  inviteMsgTimer = setTimeout(() => { inviteMsg.value = '' }, 2000)
}

onMounted(() => {
  console.log('GetFriend 接收的 slotIndex =', props.slotIndex)
  // 注册回调并请求好友列表
  ws.on(2, 'getfriend', onGetFriend)
  ws.on(3, 'invitefriend', onInviteFriend)
  try {
    const payload = { genre: 2, type: 'getfriend', uid: userStore.uid }
    ws.send(JSON.stringify(payload))
    console.log('请求好友列表:', payload)
  } catch (e) {
    console.error('请求好友列表失败:', e)
  }
})

onBeforeUnmount(() => {
  ws.off(2, 'getfriend')
  ws.off(3, 'invitefriend')
  if (inviteMsgTimer) clearTimeout(inviteMsgTimer)
})

//获取好友列表:服务的回复信息是列表，然后需要渲染到下方滚动区域
function onGetFriend(message) {
  // 期望：{ genre:2, type:'getfriend', state, data: [...] }
  if (Number(message?.state) !== 0) {
    console.error('获取好友失败:', message?.message)
    return
  }
  const list = message?.data?.friends
  if (Array.isArray(list)) {
    friends.value = list
  } else {
    friends.value = []
  }
  console.log('好友列表:', friends.value)
  // TODO: 渲染到下方滚动区域（后续实现）
}

// 收到邀请发送结果
function onInviteFriend(message){
  if (Number(message?.state) === 0) {
    showInviteMsg('邀请已发送')
  } else {
    showInviteMsg('邀请发送失败')
    console.error('邀请失败:', message?.message)
  }
}
</script>

<template>
  <div class="get-friend">
    <div class="collapse" @click="emit('collapse')">收起</div>
    <div class="top">
      <div class="slot-tip" v-if="slotIndex != null">邀请好友进入位置 {{ slotIndex }}</div>
      <div class="room-id">房间号：{{ roomStore.room_id || '—' }}</div>
      <div v-if="inviteMsg" class="invite-tip">{{ inviteMsg }}</div>
    </div>
    <div class="list">
      <div v-for="(f, i) in friends" :key="i" class="friend-item">
        <div class="col left">
          <img class="avatar" :src="`http://117.72.17.45:5500/data/profiles/${f.profile || 'default.webp'}`" :alt="f.nickname || 'avatar'" />
        </div>
        <div class="col middle">
          <div class="name">{{ f.nickname2 || '好友' }}</div>
        </div>
        <div class="col right">
          <div class="status" :class="{ online: Number(f.online) === 1 }">{{ Number(f.online) === 1 ? '在线' : '下线' }}</div>
          <button v-if="Number(f.online) === 1" class="invite-btn" @click="invite(f)">邀请</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.get-friend {
  width: 100%;
  height: 100%;
  background: #ffe6e6; /* 浅红色背景 */
  border-radius: 12px;
  position: relative;
  display: flex;
  flex-direction: column;
}
.slot-tip {
  padding: 8px 12px;
  color: #a00;
  font-weight: 700;
}
.collapse {
  position: absolute;
  top: 20px;
  right: 12px;
  color: #a00;
  cursor: pointer;
  user-select: none;
}
.top {
  padding: 16px 12px 8px 12px;
}
.room-id {
  padding: 4px 12px 0 12px;
  color: #333;
}
.invite-tip {
  padding: 6px 12px 0 12px;
  color: #0a7a0a;
  font-weight: 700;
}
.list {
  flex: 1 1 auto;
  overflow-y: auto;
  padding: 8px 12px 12px 12px;
}
.friend-item {
  display: grid;
  grid-template-columns: 56px 1fr 120px; /* 左中右 */
  align-items: center;
  gap: 12px;
  background: rgba(255,255,255,0.6);
  border-radius: 8px;
  padding: 8px 10px;
  margin-bottom: 8px;
}
.avatar {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  object-fit: cover;
  box-shadow: 0 1px 4px rgba(0,0,0,0.15);
}
.name {
  font-weight: 700;
  color: #333;
}
.right {
  display: grid;
  grid-template-rows: auto auto;
  justify-items: end;
  gap: 6px;
}
.status {
  font-size: 12px;
  color: #999;
}
.status.online { color: #16a34a; }
.invite-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 8px;
  background: #1677ff;
  color: #fff;
  cursor: pointer;
}
</style>


